package com.linshidream.intrachat.simplenio.packet.boots;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * Created on 2025/8/17 18:21
 *
 * @author linshidream
 * @version 1.0.0
 * @description 工作线程组
 */

public class PacketEventLoopGroup {

    private final PacketWorker[] workers;

    private final ExecutorService executor;

    public PacketWorker[] getWorkers() {
        return this.workers;
    }

    public PacketEventLoopGroup(int workerCount) {
        try {
            // 初始化 PacketWorker 数量
            this.workers = new PacketWorker[workerCount];
            // 使用固定大小线程池，线程数量 = workerCount
            this.executor = Executors.newFixedThreadPool(workerCount, r -> {
                Thread t = new Thread(r);
                t.setDaemon(false);
                return t;
            });

            for (int i = 0; i < workerCount; i++) {
                workers[i] = new PacketWorker();
                String name = "worker-" + i;
                int finalI = i;
                executor.execute(() -> {
                    Thread.currentThread().setName(name);
                    workers[finalI].run();
                });

                System.out.println("服务端开启了 PacketWorker[" + i + "]线程：" + name);
            }

            System.out.println("PacketEventLoop 服务端启动 PacketWorker 线程数量：" + workerCount);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }


    public void shutdownGracefully() {
        System.out.println("正在优雅关闭 PacketEventLoopGroup...");
        executor.shutdown(); // 停止接收新任务

        try {
            // 等待所有任务完成，最多 30 秒
            if (!executor.awaitTermination(30, TimeUnit.SECONDS)) {
                System.out.println("部分任务未完成，强制关闭...");
                executor.shutdownNow(); // 超时后强制关闭
            }
        } catch (InterruptedException e) {
            System.out.println("关闭过程中被打断，强制关闭...");
            executor.shutdownNow();
            Thread.currentThread().interrupt();
        }

        System.out.println("EventLoopGroup 已关闭。");
    }
}
